<template>
  <div>
    <div class="con">
      <div class="title">
        <p class="con-title">
          <span>
            <img src="@/assets/img/control/content/Group769.png" />
          </span>
          <span>发票管理</span>
        </p>
      </div>
      <div class="query">
        <el-form ref="queryParamsRef" inline :model="queryParams" label-width="90px">
          <el-form-item props="searchValue">
            <el-date-picker
              v-model="queryParams.invoiceDate"
              placeholder="请选择发票日期"
              value-format="YYYY-MM-DD HH:mm:ss"
              type="date"
            />
          </el-form-item>
          <el-form-item props="invoiceStatus">
            <el-select
              v-model="queryParams.invoiceStatus"
              placeholder="请选择发票状态"
              clearable
            >
              <el-option
                v-for="item in statusList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="querySearch"> 查询 </el-button>
            <el-button type="primary" plain @click="resetQuery">重置 </el-button>
          </el-form-item>
        </el-form>
        <div style="flex: 1">
          <el-button type="primary" style="float: right" @click="handleSetting">
            发票设置
          </el-button>
        </div>
      </div>
      <div style="margin: 10px">
        <el-text type="warning"
          >提示信息：合同需要双方线下盖章，请联系平台合同管理人员 李智
          18608303160</el-text
        >
      </div>
      <el-table border :data="dataList" header-cell-class-name="title-style">
        <el-table-column prop="orderItemId" label="支付编号" align="center" />
        <el-table-column prop="orderItemSn" label="订单编号" align="center" />
        <el-table-column label="费用类型" align="center">
          <template #default="scope">
            {{ scope.row.feesType == 1 ? "增值税普通发票" : "增值税专用发票" }}
          </template>
        </el-table-column>
        <el-table-column prop="invoiceContent" label="费用详情" align="center" />
        <el-table-column prop="amount" label="金额(元)" align="center" />
        <el-table-column prop="createTime" label="发票创建时间" align="center" />
        <el-table-column prop="invoiceStatus" label="发票状态" align="center">
          <template #default="scope">
            <div
              class="tag"
              :class="scope.row.invoiceStatus == '2' ? 'tag-blue' : 'tag-green'"
            >
              {{ scope.row.invoiceStatus == "2" ? "已开票" : "开票中" }}
              <el-button
                v-if="scope.row.invoiceStatus == '2'"
                link
                type="primary"
                @click="handleDownload(scope.row)"
              >
                (下载)
              </el-button>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template #default="scope">
            <el-button
              link
              type="primary"
              v-if="scope.row.invoiceInformationId"
              @click="handleView(scope.row)"
              >查看</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="page-footer">
        <el-pagination
          :total="total"
          v-model:current-page="queryParams.params.pageNum"
          v-model:page-size="queryParams.params.pageSize"
          layout="total, prev, pager, next"
          small
          @size-change="getList"
          @current-change="getList"
        />
      </div>
      <el-dialog v-model="invoiceShow" title="发票设置" width="500px">
        <el-form
          label-position="left"
          label-width="170px"
          ref="invoiceRef"
          :rules="invoiceRules"
          :model="invoiceForm"
        >
          <el-form-item label="发票类型" prop="invoiceType">
            <el-radio-group v-model="invoiceForm.invoiceType">
              <el-radio :label="1">增值税普通发票</el-radio>
              <el-radio :label="2">增值税专用发票</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="发票抬头（公司名称）" prop="invoiceTittle">
            <el-input v-model="invoiceForm.invoiceTittle" placeholder="请填写抬头" />
          </el-form-item>
          <el-form-item label="纳税人识别号" prop="taxpayerId">
            <el-input v-model="invoiceForm.taxpayerId" placeholder="请填写纳税人识别号" />
          </el-form-item>
          <el-form-item label="收件人姓名" prop="recipientName">
            <el-input
              v-model="invoiceForm.recipientName"
              placeholder="请填写收件人姓名"
            />
          </el-form-item>
          <el-form-item label="收件人地址" prop="recipientAddress">
            <el-input
              v-model="invoiceForm.recipientAddress"
              placeholder="请填写收件人地址"
            />
          </el-form-item>
          <el-form-item label="邮政编码" prop="zipCode">
            <el-input v-model="invoiceForm.zipCode" placeholder="请填写邮政编码" />
          </el-form-item>
          <el-form-item label="联系邮箱" prop="email">
            <el-input v-model="invoiceForm.email" placeholder="请填写联系邮箱" />
          </el-form-item>
          <el-form-item label="联系电话" prop="phoneNumber">
            <el-input v-model="invoiceForm.phoneNumber" placeholder="请填写联系电话" />
          </el-form-item>
          <el-form-item label="选择电子发票" prop="whetherElectronicInvoice">
            <el-radio-group v-model="invoiceForm.whetherElectronicInvoice">
              <el-radio :label="true">是</el-radio>
              <el-radio :label="false">否</el-radio>
            </el-radio-group>
            <div>电子发票将通过邮件发送至你填写的邮箱</div>
          </el-form-item>
        </el-form>
        <div class="centent_bottom">
          <el-button type="primary" @click="handleSubmit(invoiceRef)"> 确定 </el-button>
          <el-button @click="invoiceShow = false"> 取消 </el-button>
        </div>
      </el-dialog>
      <el-dialog title="发票详情" v-model="detailShow" width="30%">
        <el-descriptions v-if="detailRow" :column="1" border>
          <el-descriptions-item label="发票类型">
            {{ detailRow.invoiceType == 1 ? "增值税普通发票" : "增值税专用发票" }}
          </el-descriptions-item>
          <el-descriptions-item label="发票抬头（公司名称）">
            {{ detailRow.invoiceTittle || "无" }}
          </el-descriptions-item>
          <el-descriptions-item label="纳税人识别号">
            {{ detailRow.taxpayerId || "无" }}
          </el-descriptions-item>
          <el-descriptions-item label="收件人姓名">
            {{ detailRow.recipientName || "无" }}
          </el-descriptions-item>
          <el-descriptions-item label="收件人地址">
            {{ detailRow.recipientAddress || "无" }}
          </el-descriptions-item>
          <el-descriptions-item label="邮政编码">
            {{ detailRow.zipCode || "无" }}
          </el-descriptions-item>
          <el-descriptions-item label="联系邮箱">
            {{ detailRow.email || "无" }}
          </el-descriptions-item>
          <el-descriptions-item label="联系电话">
            {{ detailRow.phoneNumber || "无" }}
          </el-descriptions-item>
          <el-descriptions-item label="选择电子发票">
            {{ detailRow.whetherElectronicInvoice ? "是" : "否" }}
          </el-descriptions-item>
        </el-descriptions>
      </el-dialog>
    </div>
  </div>
</template>
<script setup lang="ts">
import { onMounted, ref } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import type { FormInstance } from 'element-plus';
import { invoiceDownload } from "@/api/cloud/index";

import {
  invoiceManagementList,
  queryInvoiceConfig,
  invoiceConfig,
  queryInvoiceDetail,
} from "@/api/control/order";

const invoiceShow = ref(false); // 发票设置弹窗
const invoiceRef = ref();
const invoiceForm = ref<any>({});
const invoiceRules = ref<any>({
  // 验证规则
  invoiceType: [{ required: true, message: "请选择发票类型", trigger: "change" }],
  invoiceTittle: [{ required: true, message: "请输入发票抬头", trigger: "blur" }],
  taxpayerId: [{ required: true, message: "请输入纳税人识别号", trigger: "blur" }],
  recipientName: [{ required: true, message: "请输入收件人姓名", trigger: "blur" }],
  recipientAddress: [{ required: true, message: "请输入收件人地址", trigger: "blur" }],
  zipCode: [
    { required: true, message: "请输入邮政编码", trigger: "blur" },
    {
      pattern: /^[0-9]{6}$/,
      message: "必须是6位数字",
      trigger: "change",
    },
  ],
  email: [
    { required: true, message: "请输入联系邮箱", trigger: "blur" },
    {
      pattern: /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\.[a-zA-Z0-9_-]{2,3}){1,2})$/,
      message: "必须是正确的邮箱格式",
      trigger: "change",
    },
  ],
  phoneNumber: [
    { required: true, message: "请输入联系电话", trigger: "blur" },
    {
      pattern: /^1(3[0-9]|5[0-3,5-9]|7[1-3,5-8]|8[0-9])\d{8}$/,
      message: "必须是正确的手机号格式",
      trigger: "change",
    },
  ],
  whetherElectronicInvoice: [
    { required: true, message: "请选择是否选择电子发票", trigger: "change" },
  ],
});

const queryParams = ref<any>({
  invoiceStatus: "",
  invoiceDate: "",
  params: {
    pageNum: 1,
    pageSize: 10,
  },
});
const dataList = ref<any>([]); // 发票列表
const total = ref(0); // 总条数
const statusList = ref<any>([
  { value: "", label: "全部" },
  { value: "1", label: "开票中" },
  { value: "2", label: "已开票" },
]);
const detailShow = ref(false); // 详情弹窗
const detailRow = ref<any>({}); // 发票详情

onMounted(() => {
  getList();
});

// 获取发票列表
const getList = () => {
  invoiceManagementList(queryParams.value).then((res: any) => {
    dataList.value = res.rows;
    total.value = res.total;
  });
};

// 搜索
const querySearch = () => {
  queryParams.value.params.pageNum = 1;
  getList();
};

// 重置
const resetQuery = () => {
  queryParams.value.invoiceDate = "";
  queryParams.value.invoiceStatus = "";
  queryParams.value.params.pageNum = 1;
  getList();
};

// 下载发票
const handleDownload = (row: any) => {
  ElMessageBox.confirm("确认下载编号为【" + row.orderItemId + "】的发票吗?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      invoiceDownload({ invoiceManagementId: row.invoiceManagementId }).then((res: any) => {
        let fileName = res.headers["content-disposition"]?.split(";")[1];
        let name = decodeURIComponent(fileName).split("=")[1];
        console.log(fileName, name);
        let alink = document.createElement("a");
        alink.href = window.URL.createObjectURL(new Blob([res.data]));
        alink.download = name;
        alink.click();
        alink.remove();
      });
    })
    .catch(() => {});
};

// 发票设置
const handleSetting = () => {
  resetInvoice();
  queryInvoiceConfig().then((res: any) => {
    Object.keys(invoiceForm.value).forEach((i) => {
      if (res.data) {
        invoiceForm.value[i] = res.data[i];
      }
    });
    invoiceShow.value = true;
  });
};

// 重置发票配置
const resetInvoice = () => {
  invoiceForm.value = {
    id: "",
    invoiceType: 1, // 发票类型
    invoiceTittle: null, // 发票抬头（公司名称）
    taxpayerId: null, // 纳税人识别号
    recipientName: null, // 收件人姓名
    recipientAddress: null, // 收件人地址
    zipCode: null, // 邮政编码
    email: null, // 联系邮箱
    phoneNumber: null, // 联系电话
    whetherElectronicInvoice: true, // 是否选择电子发票
  };
};

// 保存发票设置
const handleSubmit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid) => {
    if (valid) {
      invoiceConfig(invoiceForm.value).then(() => {
        ElMessage.success("保存成功");
        invoiceShow.value = false;
      });
    }
  });
};

// 查看发票
const handleView = (row) => {
  queryInvoiceDetail(row.invoiceInformationId).then((res: any) => {
    detailRow.value = res.data;
    detailShow.value = true;
  });
};
</script>
<style lang="less" scoped>
.con {
  width: 100%;
  height: auto;
  .con-title {
    width: 100%;
    height: 25px;
    display: flex;
    align-items: center;
    span:nth-child(1) {
      display: flex;
      align-items: center;
      img {
        width: 14px;
        height: 14px;
      }
    }
    span:nth-child(2) {
      display: flex;
      align-items: center;
      margin-left: 10px;
      font-size: 16px;
    }
  }
  .query {
    width: 100%;
    height: 50px;
    margin: 20px 0;
    display: flex;
    align-items: center;
  }
}
.content_tittle {
  width: 100%;
  height: 60px;
  display: flex;
  align-items: center;
  border-bottom: 1px solid #f2f2f2;
  margin-bottom: 20px;
  .title_name {
    font-size: 14px;
    font-weight: 600;
    margin: 0 80px 0 20px;
  }
}
.centent_bottom {
  margin-top: 30px;
  width: 100%;
  text-align: center;
}
.tag {
  display: inline-block;
  padding: 6px 15px;
  min-width: 100px;
  text-align: center;
  &::before {
    content: "";
    display: inline-block;
    width: 6px;
    height: 6px;
    border-radius: 50%;
    margin-right: 10px;
    vertical-align: middle;
  }
}
.tag-blue {
  color: #000;
  background-color: #ecf5ff;
  &::before {
    background-color: #4098ff;
  }
}
.tag-green {
  color: #50b674;
  background-color: #effff4;
  &::before {
    background-color: #50b674;
  }
}
.query {
  width: 100%;
  height: 50px;
  margin: 20px 0;
  display: flex;
}
.page-footer {
  display: flex;
  justify-content: flex-end;
  margin: 20px 0;
}
</style>

<style>
.title-style {
  height: 60px;
  background-color: #f6faff !important;
}
</style>
